﻿using System;
using System.Data;
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace Sorteo.DataObjects
{
    public class DOBase
    {
        #region Declarations

        private static Database db;

        #endregion

        #region Properties: Non-Public

        protected static Database Db
        {
            get
            {
                if (db == null)
                    db = DatabaseFactory.CreateDatabase();
                return db;
            }
        }

        #endregion

        #region Methods: Non-Public

        protected static T CreateEntityFromDataRow<T>(DataRow row) where T : new()
        {
            var entity = new T();
            var props = entity.GetType().GetProperties();

            foreach (var prop in props)
            {
                if (row.Table.Columns.Contains(prop.Name))
                {
                    object value;
                    if (prop.PropertyType == typeof(int?))
                        value = row[prop.Name];
                    else
                        value = Convert.ChangeType(row[prop.Name], prop.PropertyType);
                    prop.SetValue(entity, value, null);
                }
            }
            return entity;
        }

        #endregion
    }
}
